package org.bmi.gwt.examples.array.server;

import org.apache.log4j.Logger;
import org.bmi.gwt.examples.array.shared.Component;
import org.bmi.gwt.examples.array.shared.ObjArrayProxy;
import org.bmi.gwt.examples.array.shared.PrinterProxy;
import org.bmi.gwt.examples.array.shared.StringArrayProxy;
import org.bmi.gwt.examples.array.shared.intArrayProxy;
import org.bmi.gwt.mi.server.annotation.QueueHandler;
import org.bmi.gwt.mi.server.events.QueueEvent;
import org.bmi.gwt.mi.server.events.QueueEventHandler;
import org.bmi.gwt.mi.shared.Channel;
import org.bmi.gwt.mi.shared.MiTransaction;
import org.bmi.gwt.mi.shared.communication.var.ReturnVar;
import org.bmi.gwt.mi.shared.exceptions.InvalidArgumentException;

@QueueHandler(queueExpression = "org.bmi.gwt.mi.test.array.client")
public class ArrayEventHandler implements QueueEventHandler
{
	static protected Logger logger = Logger.getLogger(ArrayEventHandler.class);

	@Override
	public void onBound(QueueEvent event)
	{
		Channel source = event.getSourceQueueChannel();
		logger.info("Created queue: " + source.getExpression());

		MiTransaction t = source.createTransaction();
		try
		{
			PrinterProxy printerPrx = t.proxyToObject(PrinterProxy.class, "client_printer_id");

			String[] strArray = new String[] { "aaa", "bbb", "ccc" };
			int[] intArray = new int[] { 11, 22, 33 };
			Component c1 = new Component();
			c1.setStr("c1");
			Component c2 = new Component();
			c2.setStr("c2");
			Component c3 = new Component();
			c3.setStr("c3");
			Component[] objArray = new Component[] { c1, c2, c3 };

			StringArrayProxy proxy1 = t.proxyToNewObject(StringArrayProxy.class, strArray, printerPrx);
			intArrayProxy proxy2 = t.proxyToNewObject(intArrayProxy.class, intArray, printerPrx);
			ObjArrayProxy proxy3 = t.proxyToNewObject(ObjArrayProxy.class, objArray, printerPrx);

			proxy1.print1Array(strArray);
			proxy2.print1Array(intArray);
			proxy3.print1Array(objArray);

			proxy1.print2Array(new String[][] { strArray, strArray, strArray });
			proxy2.print2Array(new int[][] { intArray, intArray, intArray });
			proxy3.print2Array(new Component[][] { objArray, objArray, objArray });

			printerPrx.printLn("and with return values...");
			ReturnVar<String[][]> a1 = proxy1.createArray();
			ReturnVar<int[][]> a2 = proxy2.createArray();
			ReturnVar<Component[][]> a3 = proxy3.createArray();

			proxy1.print2Array(a1);
			proxy2.print2Array(a2);
			proxy3.print2Array(a3);
		}
		catch (InvalidArgumentException e)
		{
			e.printStackTrace();
		}

		t.commit();
	}

	@Override
	public void onCreate(QueueEvent event)
	{}

	@Override
	public void onDispose(QueueEvent event)
	{}

	@Override
	public void onUpdate(QueueEvent event)
	{}
}
